package com.honglu.backend.aop;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.honglu.backend.bo.SystemLogBo;
import com.honglu.backend.bo.UUserBo;
import com.honglu.backend.common.shiroToken.TokenManager;
import com.honglu.backend.service.impl.SystemLogServiceImpl;


/**
 * 记录用户操作到日志表
 * @author xiajiyun
 *
 */
@Aspect // 定义一个切面
@Configuration //表示程序启动会被springboot加载
public class UserInfoLogAop {
	
	private static final Logger logger = LoggerFactory.getLogger(UserInfoLogAop.class);
	
	@Autowired
	private SystemLogServiceImpl systemLogService;
	
	// 定义切点Pointcut    
	@Pointcut("execution(* com.honglu.backend.controller.*Controller.*(..))")
    public void excudeService() {
    }
    
    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();// 请求全路劲
//        String method = request.getMethod();// 具体的方法
//        String uri = request.getRequestURI();
//        String queryString = request.getQueryString();
        
        UUserBo user = TokenManager.getUser();// 获取当前登录的用户信息
        if(user != null){ // 登录状态
        	SystemLogBo systemLog = new SystemLogBo();
        	systemLog.setIp(user.getIp());
        	systemLog.setNickName(user.getNickName());// 昵称
        	systemLog.setRoleName(user.getRoleName());// 角色名称
        	systemLog.setUrl(url);
        	systemLog.setUserId(user.getId());// 用户id
        	systemLog.setUserName(user.getUserName());// 登录帐号
            systemLogService.saveEntity(systemLog);// 保存到数据表中
        }
        
//        logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);
        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        return result;
    }
	
}
